package com.commerceerp.system.api.ebay;

import com.commerceerp.system.util.StringUtils;
import com.ebay.sdk.ApiAccount;
import com.ebay.sdk.ApiContext;
import com.ebay.sdk.call.ConfirmIdentityCall;
import com.ebay.sdk.call.FetchTokenCall;
import com.ebay.sdk.call.GetSessionIDCall;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/7 0007.
 */
public class EbayTest {

    private static String appID = "weifei-getToken-SBX-c2ccbdeee-52d58fb1";
    private static String certID = "SBX-2ccbdeeee0fb-9310-4af8-9f8f-3765";
    private static String devID = "67933a5a-8a42-470a-a6dd-2909a10a3422";
    private static String ruName = "wei_fei-weifei-getToken-ywmdts";

    public static String getAuthenticateUrl() throws Exception {
        ApiContext localContext = new ApiContext();
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setApplication(appID);
        apiAccount.setCertificate(certID);
        apiAccount.setDeveloper(devID);
        localContext.getApiCredential().setApiAccount(apiAccount);
        localContext.setApiServerUrl("https://api.sandbox.ebay.com/wsapi");
        GetSessionIDCall apiCall = new GetSessionIDCall(localContext);
        apiCall.setRuName(ruName);
        String sessionID = apiCall.getSessionID();
        return "https://signin.sandbox.ebay.com/ws/eBayISAPI.dll?SignIn&" + "RuName=" + ruName
                + "&SessID=" + sessionID;

    }

    public static boolean getUserToken(String sessionID) {
        if (sessionID == null) return false;
        ApiContext localContext = new ApiContext();
        ApiAccount apiAccount = new ApiAccount();
        apiAccount.setApplication(appID);
        apiAccount.setCertificate(certID);
        apiAccount.setDeveloper(devID);
        localContext.getApiCredential().setApiAccount(apiAccount);
        localContext.setApiServerUrl("https://api.sandbox.ebay.com/wsapi");

        ConfirmIdentityCall apiCall1 = new ConfirmIdentityCall(localContext);
        apiCall1.setSessionID(sessionID);
        try {
            apiCall1.confirmIdentity();
            String userID = apiCall1.getReturnedUserID();
        } catch (Exception e) {
            e.printStackTrace();
        }

        FetchTokenCall apiCall = new FetchTokenCall(localContext);
        apiCall.setSessionID(sessionID);
        try {
            String token = apiCall.fetchToken();
            System.out.println(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void getOAuth(){
        Map params = new HashMap();
        params.put("grant_type","authorization_code");
        params.put("code","AgAAAA**AQAAAA**aAAAAA**c31yWw**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6AMkYCjDpOCqQydj6x9nY+seQ**E3MEAA**AAMAAA**u9JQ2DI+NvOhea4UMZ1goX9eJ1XyJDMt7IPbjopiAfQ8E/+7xnc2PDIILmx6rlZT1pmONrdg78bwv/D3JlaLCoUY5I4BhOclMbKUusBQ0/nqnvtlYmzhusox+OFKgAidWwr42q078eSp61ETwe+bSR3t3ZszuyDqduLbWytjMbmBoumCDQIWmlGX1Bla1Vx4TEpn9N4lKvS7ND2mU6/+2t9rTPn1ZLBqbyIpu3zK3GExpsXgVuM/Z6lkBRamlIrsedKeiX+Kvyy7KwpCNs27R5GsdiT1hYMqcIlgYY3Bpl++p3Y0QxaFjkyWbQcgJOXhvkhDtkiT3qUZFqxHjyKKycFtVJyIFW/OpIrC+ejERU2Jke5hgna1sssaCwZakQg8mE2bUzt6TWCUOY4tPuGUZOHACpvxru/+rfEYf7Qoshw0KUPRNHHuK2j7Ati6U/cHL1SPv0/KwMCwhM+1zlqYPruTw5rjXJsL0SeDMngeZwFGw8decFYNxSItesqGsas+MwP5L0+pWKpOJFcFhcFRAAWyDWHvcvJcfDpMGFDTifuNdqKB5HsIpiWCKZEfScz5nl0uewxVz1OfAVo4TFxc/zFtnDbo0mNC3HDu5nZx11PJE2PeD9RwZHLSfoL02Ga+35St5CxTYrP5C00JHxzw8y1nYzd/TkERnOh55lBK8nAUOORly/MEzknr+GtpelPqhLWO+Lfmx9f/8U8zzz76MYRfVpjdn80WAXo6idO4AYOQOqPBSf84mMnWoSqvt24x");
        params.put("redirect_uri",ruName);
        try {
            URL url = new URL("https://api.sandbox.ebay.com/identity/v1/oauth2/token");// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置接收数据的格式
            connection.setRequestProperty("Authorization", "Basic " + URLEncoder.encode(appID+":"+certID)); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(StringUtils.obj2String(params));
            out.flush();
            out.close();

            int code = connection.getResponseCode();
            InputStream is = null;
            if (code == 200) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }

            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                System.out.println(result);
            }

        } catch (IOException e) {
            System.out.println("-----------jsonPost请求失败-----------↓");
            e.printStackTrace();
            System.out.println("-----------jsonPost请求失败-----------↑");
        }
    }

    public static void main(String[] args) throws Exception {

        getOAuth();
    }

}